import { createSlice } from "@reduxjs/toolkit";

import { getToken, setToken as _setToken, removeToken } from "@/utils";

import { 
    loginApi, 
    getUserInfoApi 
} from "@/apis/user";

const userStore = createSlice({
  name: "user",
  initialState: {
    token: getToken() || "",
    userInfo: {}
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload);
    },
    setUserInfo(state, action) {
      state.userInfo = action.payload;
    },
    clearUserInfo(state) {
      state.userInfo = {};
      state.token = "";
      removeToken();
    },
  },
});

const { setToken, setUserInfo, clearUserInfo } = userStore.actions;

const fetchToken = (loginForm) => async (dispatch) => {
  try {
    const res = await loginApi(loginForm);
    dispatch(setToken(res.data.token));
  } catch (error) {
    // 处理错误，防止程序卡死
    console.error("登录请求失败:", error);
    // 可以添加 message.error("登录失败，请检查网络或稍后重试");
    throw error; // 重新抛出错误，让调用者可以处理
  }
};

const fetchUserInfo = () => async (dispatch) => {
  const res = await getUserInfoApi();
  dispatch(setUserInfo(res.data));
};
export { setToken, fetchToken, fetchUserInfo, clearUserInfo };

const userReducer = userStore.reducer;
export default userReducer;
